<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'generate_qr':
                // 生成预约码二维码
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                $verificationCode = $_GET['code'] ?? '';
                if (!$verificationCode) {
                    Response::error('缺少预约码参数');
                }
                
                // 验证预约码是否属于当前用户
                $reservation = $db->fetchOne("
                    SELECT r.*, u.id as user_id 
                    FROM reservations r 
                    JOIN users u ON r.user_id = u.id 
                    WHERE r.verification_code = ? AND u.id = ?
                ", [$verificationCode, $user['id']]);
                
                if (!$reservation) {
                    // 检查团队预约
                    $reservation = $db->fetchOne("
                        SELECT tr.*, u.id as user_id 
                        FROM team_reservations tr 
                        JOIN users u ON tr.user_id = u.id 
                        WHERE tr.verification_code = ? AND u.id = ?
                    ", [$verificationCode, $user['id']]);
                    
                    if (!$reservation) {
                        Response::error('预约码不存在或不属于您');
                    }
                }
                
                // 生成二维码数据（可以是核销链接或者预约码本身）
                $qrData = generateQRCodeData($verificationCode);
                
                Response::success([
                    'verification_code' => $verificationCode,
                    'qr_data' => $qrData,
                    'qr_url' => generateQRCodeImage($qrData)
                ], '二维码生成成功');
                break;
                
            case 'reservation_qr':
                // 根据预约ID生成二维码
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                $reservationId = (int)($_GET['reservation_id'] ?? 0);
                $type = $_GET['type'] ?? 'personal'; // personal 或 team
                
                if (!$reservationId) {
                    Response::error('缺少预约ID参数');
                }
                
                if ($type === 'team') {
                    $reservation = $db->fetchOne("
                        SELECT tr.*, u.nickname, u.real_name 
                        FROM team_reservations tr 
                        JOIN users u ON tr.user_id = u.id 
                        WHERE tr.id = ? AND u.id = ?
                    ", [$reservationId, $user['id']]);
                } else {
                    $reservation = $db->fetchOne("
                        SELECT r.*, u.nickname, u.real_name, ts.slot_name, ts.start_time, ts.end_time
                        FROM reservations r 
                        JOIN users u ON r.user_id = u.id 
                        LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                        WHERE r.id = ? AND u.id = ?
                    ", [$reservationId, $user['id']]);
                }
                
                if (!$reservation) {
                    Response::error('预约记录不存在或不属于您');
                }
                
                if (!$reservation['verification_code']) {
                    Response::error('该预约记录暂无核销码');
                }
                
                $qrData = generateQRCodeData($reservation['verification_code']);
                
                Response::success([
                    'reservation_id' => $reservationId,
                    'type' => $type,
                    'verification_code' => $reservation['verification_code'],
                    'qr_data' => $qrData,
                    'qr_url' => generateQRCodeImage($qrData),
                    'reservation_info' => [
                        'visit_date' => $reservation['visit_date'] ?? $reservation['scheduled_date'],
                        'visit_time' => $reservation['start_time'] ?? $reservation['scheduled_time'],
                        'visitor_name' => $reservation['visitor_name'] ?? $reservation['contact_name'] ?? $reservation['leader_name'],
                        'visitor_count' => $reservation['visitor_count']
                    ]
                ], '预约二维码生成成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'batch_generate':
                // 批量生成用户的所有预约二维码
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                // 获取用户的所有有效预约
                $personalReservations = $db->fetchAll("
                    SELECT r.*, ts.slot_name, ts.start_time, ts.end_time
                    FROM reservations r 
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    WHERE r.user_id = ? AND r.status = 'confirmed' AND r.verification_code IS NOT NULL
                    ORDER BY r.visit_date ASC
                ", [$user['id']]);
                
                $teamReservations = $db->fetchAll("
                    SELECT * FROM team_reservations 
                    WHERE user_id = ? AND status = 'approved' AND verification_code IS NOT NULL
                    ORDER BY scheduled_date ASC
                ", [$user['id']]);
                
                $qrCodes = [];
                
                // 生成个人预约二维码
                foreach ($personalReservations as $reservation) {
                    $qrData = generateQRCodeData($reservation['verification_code']);
                    $qrCodes[] = [
                        'type' => 'personal',
                        'reservation_id' => $reservation['id'],
                        'verification_code' => $reservation['verification_code'],
                        'visit_date' => $reservation['visit_date'],
                        'visit_time' => $reservation['start_time'] . '-' . $reservation['end_time'],
                        'slot_name' => $reservation['slot_name'],
                        'visitor_name' => $reservation['visitor_name'],
                        'visitor_count' => $reservation['visitor_count'],
                        'qr_data' => $qrData,
                        'qr_url' => generateQRCodeImage($qrData)
                    ];
                }
                
                // 生成团队预约二维码
                foreach ($teamReservations as $reservation) {
                    $qrData = generateQRCodeData($reservation['verification_code']);
                    $qrCodes[] = [
                        'type' => 'team',
                        'reservation_id' => $reservation['id'],
                        'verification_code' => $reservation['verification_code'],
                        'visit_date' => $reservation['scheduled_date'],
                        'visit_time' => $reservation['scheduled_time'],
                        'team_name' => $reservation['team_name'],
                        'contact_name' => $reservation['contact_name'] ?? $reservation['leader_name'],
                        'visitor_count' => $reservation['visitor_count'],
                        'qr_data' => $qrData,
                        'qr_url' => generateQRCodeImage($qrData)
                    ];
                }
                
                Response::success([
                    'qr_codes' => $qrCodes,
                    'total_count' => count($qrCodes)
                ], '批量生成成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}

// 生成二维码数据
function generateQRCodeData($verificationCode) {
    // 方案1: 直接返回核销链接
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
    $verificationUrl = $baseUrl . dirname($_SERVER['REQUEST_URI']) . '/../verification.html?code=' . $verificationCode;
    return $verificationUrl;
    
    // 方案2: 返回JSON数据（如果需要更复杂的数据结构）
    /*
    return json_encode([
        'type' => 'reservation_verification',
        'code' => $verificationCode,
        'url' => $verificationUrl,
        'timestamp' => time()
    ], JSON_UNESCAPED_SLASHES);
    */
}

// 生成二维码图片URL（使用第三方服务）
function generateQRCodeImage($data) {
    // 使用在线二维码生成服务
    $encodedData = urlencode($data);
    
    // 方案1: 使用qr.lianstu.com服务
    return "https://qr.lianstu.com/api.php?text=" . $encodedData . "&w=200";
    
    // 方案2: 使用chart.googleapis.com服务（需要科学上网）
    // return "https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=" . $encodedData;
    
    // 方案3: 使用api.qrserver.com服务  
    // return "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" . $encodedData;
    
    // 方案4: 本地生成（需要安装相关库）
    // 如果要本地生成，可以使用 phpqrcode 库
}

?>